<template>
  <div class="login" style="background-color: white !important">
    <a href="/">
      <div class="logo">
        <img src="../assets/web/login_1.png" />
      </div>
    </a>
    <div class="login_info">
      <div class="login_img">
        <img src="../assets/web/rw.png" alt="" width="800" />
      </div>
      <div class="login_form">
        <div class="login_title">
          <img src="../assets/web/login_t.png" />
        </div>
        <div>
          <el-form
            ref="formRef"
            size="large"
            :rules="rules"
            :model="registerData"
            autocomplete="off"
          >
            <el-form-item prop="username">
              <el-input
                :prefix-icon="User"
                placeholder="请输入用户名"
                v-model="registerData.username"
                @input="removeSpaces('username')"
              ></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                name="password"
                :prefix-icon="Lock"
                type="password"
                placeholder="请输入密码"
                v-model="registerData.password"
                @input="removeSpaces('password')"
              ></el-input>
            </el-form-item>

            <el-form-item prop="rePassword">
              <!-- <el-checkbox v-model="checked"
                ><span>登录既阅读并同意</span></el-checkbox
              > -->
            </el-form-item>

            <el-form-item>
              <el-button
                class="btn"
                type="primary btn"
                auto-insert-space
                @click="LoginM"
                >登录</el-button
              >
            </el-form-item>
            <div class="privacy-policy">
              <span
                >登录既阅读并同意<span style="color: cornflowerblue">
                  《隐私政策》
                </span></span
              >
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { User, Lock } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";

import { ref } from "vue";
import router from "@/router";
import { loginService, updatePwdService } from "@/api/user/user.js";
import { useTokenStore } from "@/store/token.js";

// 控制注册与登录表单的显示，默认显示注册
const isRegister = ref(false);

// 调用 useTokenStore 得到状态
const tokenStore = useTokenStore();

// 用于注册的数据模型
const registerData = ref({
  username: "",
  password: "",
  rePassword: "",
});

const updateData = ref({
  userPass: "",
  userName: "",
  newPass: "",
  rePass: "",
});

// 自定义验证规则：不允许包含空格
const validateNoSpaces = (rule, value, callback) => {
  if (/\s/.test(value)) {
    callback(new Error("不允许包含空格"));
  } else {
    callback();
  }
};

// 添加分类表单校验
const rules = {
  username: [
    { required: true, message: "请输入账号", trigger: "blur" },
    { min: 6, message: "用户名长度不能小于6", trigger: "blur" },
    { max: 12, message: "用户名长度不能大于12", trigger: "blur" },
    { validator: validateNoSpaces, trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能小于6", trigger: "blur" },
    { validator: validateNoSpaces, trigger: "blur" },
  ],
};

// 修改密码表单校验
const updateRules = {
  userPass: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能小于6", trigger: "blur" },
    { validator: validateNoSpaces, trigger: "blur" },
  ],
  userName: [
    { required: true, message: "请输入账号", trigger: "blur" },
    { min: 6, message: "用户名长度不能小于6", trigger: "blur" },
    { max: 12, message: "用户名长度不能大于12", trigger: "blur" },
    { validator: validateNoSpaces, trigger: "blur" },
  ],
  newPass: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能小于6", trigger: "blur" },
    { validator: validateNoSpaces, trigger: "blur" },
  ],
  rePass: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能小于6", trigger: "blur" },
    { validator: validateNoSpaces, trigger: "blur" },
  ],
};

const formRef = ref(null);
const form = ref(null);

// 数据表单的校验
const LoginM = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      login();
    } else {
      ElMessage.error("登录失败，账号密码不符合规范!");
      return false;
    }
  });
};

const login = async () => {
  let result = await loginService(registerData.value);
  // 保存 token
  tokenStore.setToken(result.data);
  ElMessage.success("登录成功!");
  router.push("/course/CourseList");
};

const updatePwd = () => {
  form.value.validate(async (valid) => {
    if (valid) {
      if (updateData.value.newPass !== updateData.value.rePass) {
        ElMessage.error("两次输入密码不一致!");
        return;
      }
      const params = new URLSearchParams();
      params.append("userPass", updateData.value.userPass);
      params.append("userName", updateData.value.userName);
      params.append("newPass", updateData.value.newPass);
      let result = await updatePwdService(params);
      if (result.code === 200) {
        ElMessage.success("修改成功!");
        window.location.reload();
      } else {
        ElMessage.error(result.msg);
      }
    }
  });
};

// 实时去除空格
const removeSpaces = (field) => {
  registerData.value[field] = registerData.value[field].replace(/\s+/g, "");
};
</script>

<style scoped>
body {
  background-color: white !important; /* 覆盖全局样式 */
}
.login {
  overflow: hidden;
}

.logo {
  width: 642px;
  height: 58px;
  margin: 31px auto 0;
}

.login_info {
  width: 1400px;
  margin: 0 auto;
  display: flex;
}

.login_form {
  width: 377px;
  height: 556px;
  border-radius: 10px;
  background: rgba(250, 250, 250, 0.4);
  box-shadow: 0px 0px 20px 0px rgba(0, 5, 193, 0.1);
  text-align: center;
  margin-top: 181px;
  margin-left: 70px;
  padding: 35px;
}

.login_title {
  margin-top: 56px;
  margin-bottom: 25px;
}

.privacy-policy {
  font-size: 14px; /* 调整字体大小 */
  color: #808080; /* 设置字体颜色 */
  margin-top: 20px; /* 调整与按钮的距离 */
  text-align: center; /* 居中对齐 */
}

.btn {
  width: 312px;
  height: 58px;
  line-height: 58px;
  color: #fff;
  background: linear-gradient(0deg, #ff3c61 0%, #ee032a 100%);
  border-radius: 29px;
  margin: 0px auto;
  text-align: center;
  cursor: pointer;
  font-size: 20px;
  letter-spacing: 10px;
  border: 0;
}
</style>
